package com.mutouren.common.mq;

import java.io.IOException;
import java.util.Map;

import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.AMQP.Exchange;
import com.rabbitmq.client.AMQP.Queue;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.QueueingConsumer;

public class RabbitMQControl {
	private static Logger errorLogger = LogManager.getLogger("SystemErrorLog");
	private Channel channel = null;
	
	public RabbitMQControl (String serverName) throws IOException {
		channel = RabbitMQSource.getChannel(serverName);
	}	
	
	public Queue.DeclareOk queueDeclare() throws IOException {
		return channel.queueDeclare();
	}	

	public Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, 
			Map<String, Object> arguments) throws IOException {
		return channel.queueDeclare(queue, durable, exclusive, autoDelete, arguments);
	}

	public Exchange.DeclareOk exchangeDeclare(String exchange, String type) throws IOException {
		return channel.exchangeDeclare(exchange, type);
	}

	public Exchange.DeclareOk exchangeDeclare(String exchange, String type,
			boolean durable, boolean autoDelete, Map<String, Object> arguments) throws IOException {
		return channel.exchangeDeclare(exchange, type, durable, autoDelete, arguments);
	}
	
	public Queue.BindOk queueBind(String queue, String exchange, String routingKey) throws IOException {
		return channel.queueBind(queue, exchange, routingKey);
	}
	
	public QueueingConsumer createConsumer() {
		return new QueueingConsumer(channel);
	}
	
	public void basicQos(int prefetchCount) throws IOException {
		this.channel.basicQos(prefetchCount);
	}
	
	public void basicAck(long deliveryTag, boolean multiple) throws IOException {
		this.channel.basicAck(deliveryTag, multiple);
	}
	
	public void publish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException {
		this.channel.basicPublish(exchange, routingKey, props, body);
	}
	
	public void consume(String queue, boolean autoAck, Consumer callback) throws IOException {
		this.channel.basicConsume(queue, autoAck, callback);
	}
	
	public Channel getChannel() {
		return this.channel;
	}	
	
	public void close() {
		try {
			if(this.channel != null && this.channel.isOpen()) {
				this.channel.close();
			}
		} catch (Throwable t) {
			errorLogger.error("RabbitMQControl.close() error!", t);
			//throw ExceptionManager.doUnChecked(t);
		}
	}
	
}












